package com.example.controller;

import com.example.domain.Record;
import com.example.domain.Resource;
import com.example.domain.User;
import com.example.service.RecordService;
import com.example.service.ResourceService;
import com.example.service.StorageService;
import com.example.service.UserService;
import com.example.util.DepartUserGet;
import com.example.util.UserGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private StorageService storageService;

    @ResponseBody
    @RequestMapping(value = "selectResourceById",method = RequestMethod.POST)
    public Resource selectResourceById(@RequestParam("rid") String id){
        try {
            Resource resource = resourceService.selectResourceById(id);
            resource.setUname(userService.selectUnameById(resource.getUid()));
            System.out.println(resource);
            return resource;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //通过用户名字查找资产，因为resource表没有uname
    //所以先模糊查找所有user表的行项目，取出符合的uid，再去资产表里面比对有没有这一行。有就是查找到的，是对的。
    public List<Resource> selectResourceByUname(String name){
        List<User> userList;
        List<Resource> resourceList = new ArrayList<>();
        try{
            userList=userService.selectUidByUname(name);
            for (int i=0;i<userList.size();i++){//获取的是名字的列表
                User user = userList.get(i);
                List<Resource> resourceList1 = resourceService.selectResourceByUid(user.getUid());
                for (int j=0;j<resourceList1.size();j++){
                    Resource resource = resourceList1.get(j);
                    resourceList.add(resource);
                }
            }
            System.out.println(resourceList);
            return resourceList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //模糊查询资产信息
    @ResponseBody
    @RequestMapping(value = "selectResourceByAll")
    public List<Resource> selectResourceByAll(@RequestParam("object")String object) throws Exception{
        List<Resource> resourceList;
        List<Resource> resourceListother;
        //第一个List是获取通过用户名字搜索的资产，第二个则是通过其他项目搜索的资产。
        if (object.equals("")){
            resourceList=resourceService.showAllResource();
        }else {
            resourceList = selectResourceByUname(object);
            resourceListother = resourceService.selectResourceByAll(object);
            //把其他搜索项整合到一起
            for (int i = 0; i < resourceListother.size(); i++) {
                Resource resource = resourceListother.get(i);
                resourceList.add(resource);
            }
        }

        //将User表里面的name赋值给resourcelist
        int length=0;
        length=resourceList.size();
        for (int i=0;i<length;i++){
            Resource resource = resourceList.get(i);
            if (resource.getUid()!=0) {
//                User user = userService.selectUnameById(resource.getUid());
//                resource.setUname(user.getUname());
                resource.setUname(userService.selectUnameById(resource.getUid()));
                resourceList.set(i,resource);
            }
        }

        return resourceList;
    }

    @ResponseBody
    @RequestMapping("showDeleteResource")
    public List<Resource> showDeleteResource(){
        List<Resource> resourceList= resourceService.showDeleteResource();
        return resourceList;
    }

    @ResponseBody
    @RequestMapping(value = "insertResource",method = RequestMethod.POST)
    public List<Resource> insert(@RequestParam("rnum") String rnum,
                          @RequestParam("name") String name,
                          @RequestParam("rtype") String rtype,
                          @RequestParam("brand") String brand,
                          @RequestParam("model") String model,
                          @RequestParam("price") String p,
                          @RequestParam("storage") String storage,
                          @RequestParam("tips") String tips,
                          @RequestParam("manage_uid") Integer manage_uid,
                                 HttpServletRequest request) {
        System.out.println(rnum);
        //类型默认是未借出，注册时间获取当日，uid因为没有借出所以不需要填写
        try{
            System.out.println(name);
            //价格设置成double，同时获取当前日期作为注册时间
            double price = Double.parseDouble(p);
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
            String registime = time.format(new Date());

            //整合成resource
            Resource resource = new Resource();
            resource.setRnum(rnum);resource.setRname(name);resource.setRstatus("未借出");
            resource.setRtype(rtype);resource.setBrand(brand);resource.setModel(model);
            resource.setRegistime(registime);resource.setTips(tips);resource.setManage_uid(manage_uid);
            resource.setPrice(price);resource.setStorage(storage);
//            Resource resource = new Resource(rnum,name,"未借出",rtype,brand,model,price,buytime,registime,tips);
            //流转日志
            //获取session，提取当前登录人的工号。
            HttpSession session = request.getSession();

            Record record = new Record();
            record.setOptype("增加资源");
            record.setUid(Integer.parseInt(session.getAttribute("id").toString()));
            record.setRid(Integer.parseInt(rnum));
            System.out.println(record);
            record.setOptime(time.format(new Date()));

            recordService.addNewRecord(record);
            resourceService.insert(resource);

            return resourceService.showAllResource();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @ResponseBody
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public List<Resource> update(@RequestParam("rnum") String rnum,
                          @RequestParam("status") String status,
                          @RequestParam("uname") String uname,
                          @RequestParam("storage") String storage,
                          @RequestParam("tips") String tips,
                          @RequestParam("oldtype") String oldtype,
                          HttpServletRequest request){

        Integer uid = null;
//        System.out.println(status);
//        if (status=="已借出") {
//            uid = userService.selectIdByUname(uname);
//            if (uid == null) {
//                return null;
//            }
//        }
//        System.out.println(uid);

        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        String borrowtime = time.format(new Date());
        Resource resource=new Resource();
        resource.setTips(tips);
        resource.setRstatus(status);
        resource.setRnum(rnum);

        try{
            if (status.equals("已借出")) {//&&!uid.equals(null)&&!uid.equals(0)
                //查询uid，如果uid找不到即为输入的名字错误
                uid = userService.selectIdByUname(uname);
                if (uid == null) {
                    return null;
                }
                System.out.println("目前状态已借出");
//                String uname = userService.selectUnameById(uid);
                resource.setStorage(null);
                resource.setBorrowtime(borrowtime);
                resource.setUid(uid);
                if (!uname.equals(null)) {

                    System.out.println(resource);

                    resourceService.borrowUpdate(resource);
                    List<Resource> resourceList = showAllResource();
                    //流转日志
                    HttpSession session = request.getSession();
                    Record record = new Record();
                    if (oldtype.equals(status)){
                        record.setRstatus("修改");
                    }else{
                        record.setRstatus("借出");
                    }
                    record.setOptype("数据修改");
                    record.setUid(Integer.parseInt(session.getAttribute("id").toString()));
                    record.setRid(Integer.parseInt(rnum));
                    record.setUserid(uid);
                    //System.out.println(record);
                    record.setOptime(time.format(new Date()));
                    recordService.addNewRecord(record);

                    resourceService.borrowUpdate(resource);
                    return resourceList;
                } else {
                    return null;
                }
            }

            //判断有无该地点,为下面的未借出的情况做铺垫。
            List<String> storagelist = storageService.selectStorage();
            int length = storagelist.size();
            boolean hasStorage=false;
            for (int i=0;i<length;i++){
                if (storage.equals(storagelist.get(i))){
                    hasStorage=true;
                    break;
                }
            }
            if (status.equals("未借出")&&hasStorage==true){

                resource.setStorage(storage);
                resource.setUid(0);

                System.out.println(resource);

                System.out.println("目前状态未借出");
                resourceService.returnUpdate(resource);
                List<Resource> resourceList = showAllResource();
                //流转日志
                HttpSession session = request.getSession();
                Record record = new Record();
                if (oldtype.equals(status)){
                    record.setRstatus("修改");
                }else{
                    record.setRstatus("归还");
                }
                record.setOptype("数据修改");
                record.setUid(Integer.parseInt(session.getAttribute("id").toString()));
                record.setRid(Integer.parseInt(rnum));
                //System.out.println(record);
                record.setOptime(time.format(new Date()));
                recordService.addNewRecord(record);

                resourceService.returnUpdate(resource);
                return resourceList;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @ResponseBody
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public List<Resource> delete(@RequestParam("id")Integer id, HttpServletRequest request){
        try {
            //List<Resource> resourceList= resourceService.delete(id);
            List<Resource> resourceList = resourceService.showAllResource();
            int length=resourceList.size();
            for (int i=0;i<length;i++){
                Resource resource = resourceList.get(i);
                if (resource.getUid()!=0) {
                    resource.setUname(userService.selectUnameById(resource.getUid()));
                    resourceList.set(i,resource);
                }
            }
            //进行流转记录
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
            //获取session，提取当前登录人的工号。
            HttpSession session = request.getSession();

            //测试部门ID，可删
            DepartUserGet departUserGet = new DepartUserGet();
            departUserGet.departIdGet(request);


            Record record = new Record();
            record.setOptype("删除资源");
            record.setUid(Integer.parseInt(session.getAttribute("id").toString()));
            record.setRid(id);
            System.out.println(record);
            record.setOptime(time.format(new Date()));

//            recordService.addNewRecord(id,1000,"删除资源",time.format(new Date()));
            recordService.addNewRecord(record);
            //引用showAllResource（）
            resourceList = showAllResource();

            return resourceList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //展示所有资产
    @ResponseBody
    @RequestMapping(value = "showAllResource")
    public List<Resource> showAllResource(){
        try{
            List<Resource> resourceList= resourceService.showAllResource();
            int length=resourceList.size();
            for (int i=0;i<length;i++){
                Resource resource = resourceList.get(i);
                if (resource.getUid()!=0) {
                    resource.setUname(userService.selectUnameById(resource.getUid()));
                    resourceList.set(i,resource);
                }
            }
            return resourceList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //展示当前登录人的所有资产
    @ResponseBody
    @RequestMapping("showMyResource")
    public List<Resource> showMyResource(HttpServletRequest request){
        HttpSession session = request.getSession();
        String uid = session.getAttribute("id").toString();
        List<Resource> resourceList = resourceService.selectResourceByUid(uid);
        return resourceList;
    }
}
